import shapefile
import sys
import os
from pointInPolygon import isPointInPolygon

## Check if valid number of arguments are passed
if len(sys.argv) != 5:
	print "Usage python WindowQuery.py <InputPolygonsShapeFile.shp> <OutputPolygonsShapeFile.shp> x_co-ordinate y_co-ordinate"
	exit(1)

## Check if arguments passed are correct
##for filename in sys.argv:
##	fileName, extension = os.path.splitext(filename)	

polygons_source_file = sys.argv[1]
polygons_destination_file = sys.argv[2]
point = []
point.append(float(sys.argv[3]))
point.append(float(sys.argv[4]))


myshp = open(polygons_source_file , "rb")
##mydbf = open(polygons_dbf_file, "rb")

r = shapefile.Reader(shp=myshp, dbf=None)

shapes = r.shapes()
w = shapefile.Writer(shapeType=5)
counter = 0

for shape in shapes:
	if shape.shapeType == 5:
		if isPointInPolygon(shape.points, point):
			w.poly(shapeType=5, parts=[shape.points])
			counter = counter + 1

print counter

if counter>0:			
	w.save(polygons_destination_file)
else:
	print 'No polygon has point inside it'





